#pragma once

#include <iostream>
#include <string>
#include <memory>
#include <sys/select.h>
#include <poll.h>
#include "Log.hpp"
#include "Socket.hpp"
#include "InetAddr.hpp"

using namespace SocketModule;
using namespace LogModule;

// #define NUM sizeof(fd_set) * 8
#define MAX 4096
const int gdefaultfd = -1;
class PollServer
{
public:
    PollServer(int port)
        : _port(port),
          _listen_socket(std::make_unique<TcpSocket>()),
          _isrunning(false)
    {
    }
    void Init()
    {
        _listen_socket->BuildTcpSocketMethod(_port);
        for (int i = 0; i < MAX; i++)
        {
            _fds[i].fd = gdefaultfd;
            _fds[i].events = 0;
            _fds[i].revents = 0;
        }
        _fds[0].fd = _listen_socket->Fd();
        _fds[0].events |= POLLIN;
    }

    void Loop()
    {
        // fd_set rfds; // 读文件描述符
        int timeout = -1;
        _isrunning = true;
        while (_isrunning)
        {
            int n = poll(_fds, MAX, timeout);
            // FD_ZERO(&rfds);
            // struct timeval timeout = {10, 0};

            // int maxfd = gdefaultfd;
            // for (int i = 0; i < MAX; i++)
            // {
            //     if (_fd_array[i] == gdefaultfd)
            //     {
            //         continue;
            //     }
            //     FD_SET(_fd_array[i], &rfds); // 包含listensockfd
            //     if (maxfd < _fd_array[i])
            //     {
            //         maxfd = _fd_array[i];
            //     }
            // }

            // int n = select(maxfd + 1, &rfds, nullptr, nullptr, &timeout);
            switch (n)
            {
            case 0:
                std::cout << "time out..." << std::endl;
                break;
            case -1:
                perror("select");
                break;
            default:
                // std::cout << "有事件就绪...,timeout: " << timeout.tv_sec << ":" << timeout.tv_usec << std::endl;
                std::cout << "有事件就绪...,timeout:" << std::endl;
                // Dispatcher(rfds);
                Dispatcher();
                break;
            }
        }
        _isrunning = false;
    }
    void Accepter()
    {
        InetAddr client;
        auto newsocket = _listen_socket->Accepter(&client);
        if (newsocket->Fd() < 0)
            return;
        else
        {
            std::cout << "获得了一个新链接: " << newsocket->Fd() << "client info:" << client.Addr() << std::endl;
            int pos = -1;
            for (int j = 0; j < MAX; j++)
            {
                if (_fds[j].fd == gdefaultfd)
                {
                    pos = j;
                    break;
                }
            }
            if (pos == -1)
            {
                LOG(LogLevel::ERROR) << "服务器已经满了...";
                close(newsocket->Fd());
            }
            else
            {
                _fds[pos].fd = newsocket->Fd();
                _fds[pos].events = POLLIN;
            }
        }
    }

    void Recver(int who)
    {
        char buffer[1024];
        ssize_t n = recv(_fds[who].fd, buffer, sizeof(buffer) - 1, 0); // 会不会被阻塞？就绪了
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "client# " << buffer << std::endl;
            // 把读到的信息，在回显会去
            std::string message = "echo# ";
            message += buffer;
            send(_fds[who].fd, message.c_str(), message.size(), 0); // bug
        }
        else if (n == 0)
        {
            LOG(LogLevel::DEBUG) << "客户端退出, sockfd: " << _fds[who].fd;
            close(_fds[who].fd);
            _fds[who].fd = gdefaultfd;
        }
        else
        {
            LOG(LogLevel::DEBUG) << "客户端读取出错, sockfd: " << _fds[who].fd;
            close(_fds[who].fd);
            _fds[who].fd = gdefaultfd;
        }
    }
    void Dispatcher()
    {
        for (int i = 0; i < MAX; i++)
        {
            if (_fds[i].fd == gdefaultfd)
            {
                continue;
            }
            if (_fds[i].fd == _listen_socket->Fd())
            {
                if (_fds[i].revents & POLLIN)
                {
                    Accepter();
                }
            }
            else
            {
                if (_fds[i].revents & POLLIN)
                {
                    Recver(i);
                }
            }
        }
    }

    // void Dispatcher(fd_set& rfds)
    // {
    //     for(int i = 0;i<NUM;i++)
    //     {
    //         if(_fd_array[i]==gdefaultfd)
    //         {
    //             continue;
    //         }
    //         if(_fd_array[i]==_listen_socket->Fd())
    //         {
    //             if(FD_ISSET(_fd_array[i],&rfds))
    //             {
    //                 Accepter();
    //             }
    //         }
    //         else
    //         {
    //             if(FD_ISSET(_fd_array[i],&rfds))
    //             {
    //                 Recver(i);
    //             }
    //         }
    //     }
    // }
    ~PollServer()
    {
    }
    void TestFd()
    {
        std::cout << "pollfd: ";
        for (int i = 0; i < MAX; i++)
        {
            if (_fds[i].fd == gdefaultfd)
                continue;
            std::cout << _fds[i].fd << "[" << Events2Str(_fds[i].events) << "] ";
        }
        std::cout << "\n";
    }
    std::string Events2Str(short events)
    {
        std::string s = ((events & POLLIN) ? "EPOLLIN" : "");
        s += ((events & POLLOUT) ? "POLLOUT" : "");
        return s;
    }

private:
    uint16_t _port;
    std::unique_ptr<Socket> _listen_socket;
    bool _isrunning;
    // int _fd_array[NUM]; // 辅助数组
    struct pollfd _fds[MAX];
};